<template>
  <div class="app-container dialog-w80">
    <div class="customContainer">
      <el-form :inline="true" :model="formInline" class="demo-form-inline" size="small">
        <el-form-item>
          <el-select placeholder="选择类型" v-model="formInline.species" filterable>
            <el-option v-for="item in type_list" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select placeholder="供货渠道:" v-model="formInline.from" @change="fromChange" filterable>
            <el-option v-for="item in from" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-input v-model="formInline.accessories_id" placeholder="请输入物品编号/名称" @keyup.enter.native="searchClick"></el-input>
        </el-form-item>
        <el-form-item>
          <dj-button size="small" @search="searchClick">
            <template #default>搜索</template>
          </dj-button>
        </el-form-item>
      </el-form>

      <!-- 列表 -->
      <el-table highlight-current-row :data="list" v-loading.body="listLoading" border size="small">
        <el-table-column align="center" label="图片" width="80">
          <template slot-scope="scope">
            <vue-preview class="preview" :slides="scope.row.imgList"></vue-preview>
          </template>
        </el-table-column>
        <el-table-column align="center" label="物品编号" prop="id"></el-table-column>
        <el-table-column align="center" label="神采编号" prop="no_obsolete"></el-table-column>
        <el-table-column align="center" label="物品名称" prop="name"></el-table-column>
        <el-table-column align="center" label="类别" prop="type_name"></el-table-column>
        <el-table-column align="center" label="采购价（元）" prop="money_sell"></el-table-column>
        <el-table-column align="center" label="前台销售">
          <template slot-scope="scope">
            {{scope.row.is_store_on_sale==1?'支持':'-'}}
          </template>
        </el-table-column>
        <el-table-column align="center" label="可采购数">
          <template slot-scope="scope">
            {{!scope.row.num? '-' : scope.row.num}}
          </template>
        </el-table-column>
        <el-table-column align="center" label="已订购数" prop="on_order"></el-table-column>
        <el-table-column align="center" label="建议订购数">
          <template slot-scope="scope">
            <span
              v-if="scope.row.is_on_sale!=1">{{scope.row.on_order=="-"?"-":((scope.row.accessories_num*1-scope.row.on_order*1)>0?(scope.row.accessories_num*1-scope.row.on_order*1):0)}}</span>
            <span
              v-if="scope.row.is_on_sale==1">{{scope.row.on_order=="-"?"-":((scope.row.num*1-scope.row.on_order*1)>'0'?scope.row.num*1-scope.row.on_order*1:0)}}</span>
          </template> </el-table-column> <!-- 列表的操作按钮 -->

        <el-table-column align="center" label="订购" width="60">
          <template slot-scope="scope">
            <el-button style="font-size:28px" :disabled="scope.row.in_car==1" type="text"
              @click="addcar(scope.row.id,formInline.from,scope.row.box_num,scope.$index)">
              <i class="el-icon-circle-plus"></i>
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 弹框 -->
      <el-dialog :close-on-click-modal="false" class="dialog_table" title="购物车" :visible.sync="show_carList" style="margin-top:-5vh" @close="car_close">
        <div class="dialogInContainer" v-loading="dialogLoading">
          <div class="customHeader">
            <el-select placeholder="请选择收货地址" filterable v-model="houseVal" @change="houseChange">
              <el-option v-for="item in houseList" :key="item.house_id" :label="item.name" :value="item.house_id"></el-option>
            </el-select>
            <br> &#x3000;{{houseInfo.name}}　{{houseInfo.address}}　{{houseInfo.linkman}}　{{houseInfo.phone}}
          </div>
          <el-table highlight-current-row :data="carList" v-loading.body="listLoading" border size="small">
            <el-table-column align="center" label="图片" width="70">
              <template slot-scope="scope">
                <img :src="scope.row.thumb" width="50" height="50" alt="">
              </template>
            </el-table-column>
            <el-table-column align="center" label="物品信息" prop="accessories_id">
              <template slot-scope="scope">
                {{scope.row.name}}
                <br>物品编号{{scope.row.accessories_id}}
              </template>
            </el-table-column>
            <el-table-column align="center" label="类别" prop="type_name"></el-table-column>
            <el-table-column align="center" label="数量(个)">
              <template slot-scope="scope">
                <i v-if="scope.row.is_on_sale==0" class="el-icon-error danger">已下架</i>
                <el-input onkeypress="return event.which>=48&&event.which<=57" type="number" onmousewheel="return false;" v-if="scope.row.is_on_sale*1>0"
                  v-model="scope.row.shop_num" placeholder="数量" @input="count"></el-input>
              </template>
            </el-table-column>
            <el-table-column align="center" label="可采购数" prop="accessories_num">
              <template slot-scope="scope">
                <span v-if="scope.row.is_on_sale!=1">{{scope.row.accessories_num}}</span>
                <span v-if="scope.row.is_on_sale==1">{{scope.row.num}}</span>
              </template>
            </el-table-column>
            <el-table-column align="center" label="已订购数" prop="on_order"></el-table-column>
            <el-table-column align="center" label="建议订购数">
              <template slot-scope="scope">
                <span v-if="scope.row.is_on_sale!=1">
                  {{scope.row.on_order=="-"?"-":(((scope.row.accessories_num*1-scope.row.on_order*1)>0)?(scope.row.accessories_num*1-scope.row.on_order*1):0)}}
                </span> 
                <span v-if="scope.row.is_on_sale==1">
                  {{scope.row.on_order=="-"?"-":((scope.row.num - scope.row.on_order) > 0 ? (scope.row.num-scope.row.on_order):0)}} 
                </span>
              </template>
            </el-table-column>
            <el-table-column align="center" label="采购单价">
              <template slot-scope="scope">
                <span v-if="scope.row.is_on_sale!=1">{{scope.row.accessories_money_sell*1>0?scope.row.accessories_money_sell:'-'}}</span>
                <span v-if="scope.row.is_on_sale==1">{{scope.row.money_sell*1>0?scope.row.money_sell:'-'}}</span>
              </template>
            </el-table-column>
            <el-table-column align="center" label="金额小计">
              <template slot-scope="scope">
                <span v-if="scope.row.is_on_sale!=1">
                  {{scope.row.shop_num*1*scope.row.accessories_money_sell*1|keepTwoNum}}</span>
                <span v-if="scope.row.is_on_sale==1">
                  {{scope.row.shop_num*1*scope.row.money_sell*1|keepTwoNum}}</span>
              </template>
            </el-table-column>
            <!-- 列表的操作按钮 -->
            <el-table-column align="center" label="操作">
              <template slot-scope="scope">
                <el-button @click="delClick(scope.row.accessories_id,scope.$index,scope.row.is_on_sale)" type="danger" icon="el-icon-delete" size="mini">
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <!-- 自定义底部 -->
          <div class="bottom_box">
            <el-button type="text" size="small" @click="delCarListClick()">清空购物车</el-button>
            <el-button class="pull-right" size="small" type="primary" :loading="btnLoding" @click="saveClick()">提交订单</el-button>
            <p class="pull-right" style="line-height:0">礼品种类:{{car_accessories_num}} 　订单总数:{{totalOrder}}
              　合计:{{totalPrice|keepTwoNum}}</p>
          </div>
        </div>
      </el-dialog>
    </div>

    <!-- 自定义底部 -->
    <div class="bottom_box">
      <el-pagination class="pull-left" background @current-change="handleCurrentChange" :current-page.sync="currentPage" :page-size="20"
        layout="prev, pager, next, jumper" :total="totalDataNumber">
      </el-pagination>
      <el-badge :value="car_accessories_num" class="item pull-right">
        <el-button type="text" size="small" @click="goodscar()">
          <svg-icon style="font-size:18px" icon-class="car" />
        </el-button>
      </el-badge>
    </div>
  </div>
</template>

<script>
import { getPage, getList, addcar_submit, car, getHouse, getHouseInfo, delaccessories, delCarList, get_goods_type, save } from '@/api/goodsflow/pj_platform.js';
export default {
  data() {
    return {
      dialogLoading: false,
      listLoading: false,
      btnLoding: false,
      car_accessories_num: '',
      show_carList: false,
      from: [
        { id: 2, name: '中央仓' },
        { id: 1, name: '供应商' }
      ],
      currentPage: 1,
      totalDataNumber: 0,
      totalPrice: '',
      totalOrder: '',
      type_list: null,
      houseInfo: {},
      houseList: null,
      houseVal: '',
      formInline: {
        from: 2,
        accessories_id: '',
        species: ''
      },
      list: null,
      carList: null,
      saveForm: {
        species: '',
        house_id: '',
        order_list: []
      },
      errNum: '',
      type1: [],
      type2: []
    };
  },
  beforeRouteEnter(to, from, next) {
    next(vm => {
      //当进入组件之前，执行 beforRouteEnter 路由钩子函数 ,//参数vm就是当前组件的实例。
      if (!vm.type_list) {
        vm.getGoods();
      }
    });
  },
  // created() {
  //     this.getGoods();
  // },
  methods: {
    getGoods() {
      get_goods_type({ category_id: this.$route.meta.id }).then(response => {
        response.forEach(item => {
          if (item.name == '配件类物品') {
            item.id = 1;
          } else if (item.name == '财务类物品') {
            item.id = 2;
          } else if (item.name == '其他类物品') {
            item.id = 3;
          }
        });
        this.type_list = response;
        this.formInline.species = response.length > 0 ? response[0].id : '';
      });
    },
    // 计算购物车
    count() {
      var totalPrice = 0; //临时总价
      var totalOrder = 0;
      this.carList.forEach(function(val, index) {
        if (val.is_on_sale * 1 > 0) {
          totalPrice += val.shop_num * 1 * val.money_sell * 1; //累计总价
          totalOrder += val.shop_num * 1;
        }
      });
      this.totalPrice = parseFloat(totalPrice);
      this.totalOrder = parseFloat(totalOrder);
    },
    // 购物车提交
    saveClick() {
      if (this.carList.length == 0) {
        this.$message({ type: 'error', message: '大佬，你购物车空空如也' });
        return;
      }
      this.errNum = '';
      if (!this.houseVal) {
        this.$message({ type: 'error', message: '请先选择收货地址!' });
        return;
      }
      this.saveForm = {
        type: '',
        house_id: this.houseVal,
        order_list: [],
        species: this.formInline.species
      };
      const that = this;
      this.carList.forEach(function(val, index) {
        if (val.supplier_type == 1) {
          that.type1.push(val.supplier_type);
        } else {
          that.type2.push(val.supplier_type);
        }
      });
      if (that.type2.length > 0) {
        if (that.type1.length > 0) {
          that.$message({ type: 'error', message: '不同供货渠道的商品不能在同一订单下货!' });
          return;
        }
        this.carList.forEach(function(val, index) {
          if (val.shop_num * 1 > val.accessories_num * 1) {
            that.errNum = true;
            return false;
          }
          if (val.is_on_sale * 1 > 0) {
            if (val.shop_num * 1 > 0 && /^\d+$/.test(val.shop_num)) {
              that.saveForm.order_list.push({
                total_num: val.shop_num,
                accessories_id: val.accessories_id,
                type: val.supplier_type,
                look_money: val.is_on_sale == 1 ? val.money_sell : accessories_money_sell
              });
            }
          }
        });
      } else {
        this.carList.forEach(function(val, index) {
          if (val.is_on_sale * 1 > 0) {
            if (val.shop_num * 1 > 0 && /^\d+$/.test(val.shop_num)) {
              that.saveForm.order_list.push({
                total_num: val.shop_num,
                accessories_id: val.accessories_id,
                type: val.supplier_type,
                look_money: val.is_on_sale == 1 ? val.money_sell : accessories_money_sell
              });
            }
          }
        });
      }
      if (that.errNum == true) {
        that.$message({ type: 'error', message: '订货量应小于库存量!' });
        return;
      }
      if (that.saveForm.order_list.length == 0 || that.saveForm.order_list.length != that.car_accessories_num) {
        that.$message({ type: 'error', message: '请将数量填写完整,并且数量只能为整数!' });
        return;
      }
      this.saveForm.type = this.saveForm.order_list[0].type;
      this.btnLoding = true;
      save(this.saveForm)
        .then(response => {
          this.$message({
            type: response.code == 1 ? 'success' : 'error',
            message: response.message
          });
          if (response.code == 1) {
            this.btnLoding = false;
            this.type1 = [];
            this.type2 = [];
            this.show_carList = false;
          }
        })
        .catch(() => {
          this.btnLoding = false;
        });
    },
    car_close() {
      this.handleCurrentChange(this.currentPage);
    },
    // 清空购物车
    delCarListClick() {
      delCarList({ type: this.formInline.from, species: this.formInline.species }).then(response => {
        this.type1 = [];
        this.type2 = [];
        this.carList = [];
        this.count();
      });
    },
    delClick(id, index, is_on_sale) {
      delaccessories({ accessories_id: id, type: this.formInline.from, species: this.formInline.species }).then(response => {
        this.$message({
          type: response.code == 1 ? 'success' : 'error',
          message: response.message
        });
        if (response.code == 1) {
          this.errNum = '';
          this.type1 = [];
          this.type2 = [];
          this.carList.splice(index, 1);
          if (is_on_sale) {
            this.car_accessories_num--;
          }
          this.count();
        }
      });
    },
    fromChange() {
      this.fetchData();
    },
    houseChange() {
      this.houseInfo = '';
      getHouseInfo({ id: this.houseVal }).then(response => {
        this.houseInfo = response;
      });
    },
    searchClick() {
      this.fetchData();
    },
    addcar(accessories_id, type, num, index) {
      var data = {
        accessories_id: accessories_id,
        type: type,
        num: num,
        species: this.formInline.species
      };
      this.listLoading = true;
      addcar_submit(data)
        .then(response => {
          this.listLoading = false;
          if (response.code == 1) {
            this.list[index].in_car = 1;
            this.car_accessories_num += 1;
            this.$message({
              type: 'success',
              message: '添加成功'
            });
          }
        })
        .catch(res => {
          this.listLoading = false;
        });
    },
    goodscar() {
      this.show_carList = true;
      this.dialogLoading = true;
      car({ type: this.formInline.from, species: this.formInline.species })
        .then(response => {
          this.car_accessories_num = response.filter(item => {
            return item.is_on_sale * 1 > 0;
          }).length;
          this.carList = response;
          this.count();
          this.dialogLoading = false;
        })
        .catch(res => {
          this.dialogLoading = false;
        });
      getHouse({ category_id: 133 }).then(response => {
        this.houseList = response;
      });
    },
    // 列表
    fetchData() {
      this.listLoading = true;
      this.currentPage = 1;
      getPage(this.formInline)
        .then(response => {
          this.currentPage = 1;
          this.totalDataNumber = response.page * 20;
          getList(this.formInline)
            .then(response => {
              this.car_accessories_num = response.length > 0 ? response[0].car_accessories_num : '';
              response.forEach(function(val, i) {
                val.imgList = [
                  {
                    src: val.img,
                    msrc: val.thumb,
                    w: 1200,
                    h: 900
                  }
                ];
              });
              this.list = response;
              this.listLoading = false;
            })
            .catch(() => {
              this.listLoading = false;
            });
        })
        .catch(() => {
          this.listLoading = false;
        });
    },
    // 分页
    handleCurrentChange(val) {
      this.listLoading = true;
      getList(this.formInline, val)
        .then(response => {
          this.car_accessories_num = response.length > 0 ? response[0].car_accessories_num : '';
          response.forEach(function(val, i) {
            val.imgList = [
              {
                src: val.img,
                msrc: val.thumb,
                w: 1200,
                h: 900
              }
            ];
          });
          this.list = response;
          this.listLoading = false;
        })
        .catch(() => {
          this.listLoading = false;
        });
    }
  }
};
</script>